/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://gitee.com/newgolo/embedme.git
 * Copyright 2014~2020 @ ShenZhen ,China
*******************************************************************************/
#include "libemb/Tracer.h"
#include "libembx/CANPort.h"

namespace libembx{
CANPort::CANPort():
m_name("")
{
}
CANPort::~CANPort()
{
}
bool CANPort::open(const char* name, int baudrate)
{
	int state;
	if (name==NULL || baudrate<=0)
	{
		return false;
	}
	if (can_get_state(name, &state)!=0)
	{
		TRACE_ERR_CLASS("get can state error,%s!\n",name);
		return false;
	}
	/* 如果CAN总线已经启动,需要先停止 */
	if (state!=CANSTATE_STOPPED)
	{
		if (can_do_stop(name)!=0)
		{
			TRACE_ERR_CLASS("stop can error,%s!\n",name);
			return false;
		}
	}
	/* 设置波特率并启动CAN总线 */
	if(can_set_bitrate(name, baudrate)!=0)
	{
		TRACE_ERR_CLASS("set can baudrate error,%s:%d!\n",name,baudrate);
		return false;
	}
	if (can_do_start(name)!=0)
	{
		TRACE_ERR_CLASS("start can error,%s!\n",name);
		return false;
	}
	m_name = std::string(name);
	return true;
}
void CANPort::close()
{
	if (!m_name.empty())
	{
		can_do_stop(CSTR(m_name));
	}
}

void CANPort::restart()
{
	if (!m_name.empty())
	{
		can_do_restart(CSTR(m_name));
	}
}


int CANPort::getState()
{
	if (m_name.empty())
	{
		return -1;
	}
	int state;
	if (can_get_state(CSTR(m_name), &state)!=0)
	{
		TRACE_ERR_CLASS("get can state error,%s!\n",CSTR(m_name));
		return -1;
	}
	return state;
}

}

